package com.voltmao.webpro.utils;

import com.google.gson.*;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class StringUtils {

    public static final String pattern = "yyyy-MM-dd HH:mm";
    public static final String FULL_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String MINUTES_PATTERN = "MM-dd";

    public static String uuid32() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String uuid36() {
        return UUID.randomUUID().toString();
    }

    public static String splitArray(String text){
        int beginIndex = text.indexOf("[");
        int endIndex = text.lastIndexOf("]");
        return text.substring(beginIndex,endIndex+1);
    }

    public static boolean mapIsEmpty(Map<String, Object> map){
        return map == null || map.size()<1;
    }

    public static String randomIntLength(int length) {
        length = length - 1;
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        StringBuilder reStr = new StringBuilder();

        for (int i = 0, size = length; i < size; i++) {
            reStr.append(arr[new Random().nextInt(arr.length)]);
        }

        return reStr.toString();
    }

    public static String valueOf(Object obj) {
        if (obj == null)
            return null;
        return String.valueOf(obj);
    }

    /**
     * 字符串转换为int,如不能转换设置为默认值
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static int parseInt(String str, int defaultValue) {
        if (str == null || str.length() == 0) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str);
        } catch (Throwable e) {
            return defaultValue;
        }
    }

    /**
     * @param obj
     * @param defaultStr
     * @return
     */
    public static String parseStr(Object obj, String defaultStr) {
        if (obj == null || StringUtils.isEmpty(obj + "")) {
            return defaultStr;
        }

        return obj + "";
    }


    public static String objectToJsonDateSerializer(Object ts,
                                                    final String dateformat) {
        String jsonStr = null;
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class,
                new JsonSerializer<Date>() {
                    public JsonElement serialize(Date src,
                                                 Type typeOfSrc,
                                                 JsonSerializationContext context) {
                        if (StringUtils.isEmpty(dateformat)) {
                            return new JsonPrimitive(src.getTime());
                        } else {
                            SimpleDateFormat format = new SimpleDateFormat(
                                    dateformat);
                            return new JsonPrimitive(format.format(src));
                        }
                    }
                }).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        if (gson != null) {
            jsonStr = gson.toJson(ts);
        }
        return jsonStr;
    }

    private StringUtils() {

    }


    public static boolean isEmpty(String name) {
        return name == null || "".equals(name) || name.length()==0 || "null".equals(name);
    }

    /**
     * 判断不为空
     *
     * @param name
     * @return
     */
    public static boolean isNotEmpty(Object name) {
        return !(name == null || "".equals(name));

    }

    /**
     * 将url参数转换成map
     *
     * @param url *.html?aa=11&bb=22&cc=33
     * @return
     */
    public static Map<String, Object> getUrlParams(String url) {

        String[] urlArr = url.split("[?]");
        String param = urlArr.length == 2 ? urlArr[1] : "";

        Map<String, Object> map = new HashMap<String, Object>(0);
        if (StringUtils.isEmpty(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }


    /**
     * 将url参数转换成map
     *
     * @param params aa=11&bb=22&cc=33
     * @return
     */
    public static String getUrlParams(Map<String, Object> params) {
        if (params == null) {
            return "";
        }

        List<String> result = new LinkedList<>();

        Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();

            result.add(entry.getKey() + "=" + entry.getValue());
        }

        return org.apache.commons.lang3.StringUtils.join(result.toArray(), "&");
    }

    /**
     * 解码
     *
     * @param str
     * @param enc
     * @return
     */
    public static String getUrlDecode(String str, String enc) {
        String reStr = "";
        try {
            reStr = URLDecoder.decode(str, enc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return reStr;
    }

    /**
     * 转码
     *
     * @param str
     * @param enc
     * @return
     */
    public static String getUrlEncode(String str, String enc) {
        String reStr = "";
        try {
            reStr = URLEncoder.encode(str, enc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return reStr;
    }

    /**
     * @param list
     * @param attr
     * @param val
     * @return
     */
    public static List<Map<String, Object>> listForAttrVal(List<Map<String, Object>> list, String attr, String val) {
        List<Map<String, Object>> li = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (val.equals(list.get(i).get(attr))) {
                li.add(list.get(i));
            } else if (null == list.get(i).get(attr) && val.equals("")) {
                li.add(list.get(i));
            }
        }
        return li;
    }

    public static void main(String[] args) {
//		System.out.println(StringUtils.randomIntLength(10));

//		Map<String,Object> params = new HashMap<>();
//		params.put("openId","sdfsdfsss");
//
//		System.out.println(StringUtils.getUrlParams(params));
//
//
//
        System.out.println(StringUtils.fillZeroToInt(11,4));
//        System.out.println(StringUtils.substringByLastChar("http://localhost:8080/api/login/index.html", "/"));

    }

    public static String getValue(Object obj) {
        if (obj == null) {
            return "";
        }

        return obj + "";
    }


    public static String substringByLastChar(String str, String lastChar) {
        if (str.lastIndexOf(lastChar) == -1) {

            return str;
        }

        return str.substring(0, str.lastIndexOf(lastChar) + 1);
    }

    /**
     * 将数字i进行前充0，达到总数为size
     * @param i 大于0
     * @param size 长度
     * @return 前充0的字符串
     */
    public static String fillZeroToInt(Integer i, int size){
        int size2 = i.toString().length();
        int size3 = size -size2;
        StringBuilder zeros = new StringBuilder();
        if(size3 < 0) {
            return i.toString();
        } else {
            for(int k=0;k<size3;k++){
                zeros.append("0");
            }
            zeros.append(i.toString());
            return zeros.toString();
        }
    }
}
